<template>
    <el-card>
        <div slot="header">评论</div>
        <el-table border stripe :data="data" max-height="300">
            <el-table-column label="用户" prop="user.username" width="120">
                <template slot-scope="scope">
                    <el-button type="text" @click="$router.push(`/user/${scope.row.user.id}`)">
                        {{scope.row.user.username}}
                    </el-button>
                    <div class="gray">{{scope.row.time}}</div>
                </template>
            </el-table-column>
            <el-table-column label="内容" prop="content"/>
        </el-table>
        <p class="report-comment-form" v-loading="form.loading">
            <el-input type="textarea" v-model="form.content" placeholder="填入评论内容"/>
            <br/>
            <el-button @click="post" :loading="form.posting" type="primary">评论</el-button>
        </p>
    </el-card>
</template>

<script>
    export default {
        name: "report_comment",
        props: {
            report: {required: true},
        },
        data() {
            return {
                loading: true,
                data: [],
                form: {loading: false, content: ''},
            };
        },
        methods: {
            fetch() {
                this.$http.get(`/api/report-comment/${this.report.id}/${Date.now()}`).then(res => {
                    const data = res.data;
                    data.forEach(item => {
                        item.created_at = new Date(item.created_at).getTime();
                        item.time = moment(item.created_at).calendar();
                        this.data.push(item);
                    });
                });
            },
            post() {
                this.form.loading = true;
                this.$http.post(`/api/report-comment/${this.report.id}`, {content: this.form.content})
                    .then(res => {
                        this.form.loading = false;
                        this.data.push({
                            user: this.$store.state.user,
                            content: this.form.content,
                            time: moment().calendar()
                        });
                        this.$message.success('成功发表评论');
                        this.form.content = '';
                    })
                    .catch(err => {
                        this.form.loading = false;
                        this.$message.error(err.response.data);
                    });
            },
        },
        watch: {
            report() {
                this.fetch();
            },
        }
    }
</script>

<style scoped>
    .gray {
        font-size: small;
        color: #999;
    }

    .report-comment {

    }

    .report-comment-form {
        width: 50%;
    }

    @media (max-width: 500px) {
        .report-comment-form {
            width: 100%;
        }
    }
</style>